package com.anjian.bamin.anjiandianzimap.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.aiton.administrator.shane_library.shane.ZjbBaseActivity;
import com.aiton.administrator.shane_library.shane.app.SysApplication;
import com.aiton.administrator.shane_library.shane.widget.MyProgressDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.nearby.NearbySearch;
import com.amap.api.services.nearby.NearbySearchFunctionType;
import com.anjian.bamin.anjiandianzimap.R;
import com.anjian.bamin.anjiandianzimap.contant.Constant;

public class ChooseAddressActivity extends ZjbBaseActivity implements View.OnClickListener {

    MapView mMapView = null;
    private AMap AMap;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    private NearbySearch.NearbyQuery mQuery;
    private MyProgressDialog mProgressDialog;
    private String mAddress;
    private LatLng mLocationLatLng;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    double latitude = amapLocation.getLatitude();//获取纬度
                    double longitude = amapLocation.getLongitude();//获取经度
                    if (mProgressDialog != null && mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();//定位后取消progressDialog
                        mProgressDialog = null;
                    }
                    mAddress = amapLocation.getAddress();
                    mLocationLatLng = new LatLng(latitude, longitude);
                    mTextView_companyName.setText(mAddress);
                    moveCenterMarker(mLocationLatLng);
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }

    };
    private TextView mTextView_companyName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_address);
        init();
        initMap(savedInstanceState);
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void findID() {
        mTextView_companyName = (TextView) findViewById(R.id.textView_companyName);
    }

    @Override
    protected void initViews() {

    }

    private void initMap(Bundle savedInstanceState) {
        setProgressDialog("正在定位……");
//在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMapView = (MapView) findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        AMap = mMapView.getMap();
        //设置默认定位按钮是否显示
        UiSettings uiSettings = AMap.getUiSettings();
        uiSettings.setMyLocationButtonEnabled(false);
        uiSettings.setZoomControlsEnabled(false);
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        AMap.setMyLocationEnabled(true);
        AMap.moveCamera(CameraUpdateFactory.zoomBy(6));
        //设置搜索条件
        mQuery = new NearbySearch.NearbyQuery();
        AMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    final LatLng position = AMap.getCameraPosition().target;

                    //设置搜索的中心点
                    mQuery.setCenterPoint(new LatLonPoint(position.latitude, position.longitude));
                    //设置搜索的坐标体系
                    mQuery.setCoordType(NearbySearch.AMAP);
                    //设置搜索半径
                    mQuery.setRadius(10000);
                    //设置查询的时间
                    mQuery.setTimeRange(1000);
                    //设置查询的方式驾车还是距离
                    mQuery.setType(NearbySearchFunctionType.DRIVING_DISTANCE_SEARCH);
                    //调用异步查询接口
                    NearbySearch.getInstance(getApplicationContext())
                            .searchNearbyInfoAsyn(mQuery);


                    GeocodeSearch geocodeSearch = new GeocodeSearch(ChooseAddressActivity.this);
                    //地理编码查询结果监听接口设置
                    geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                        @Override
                        //根据给定的经纬度和最大结果数返回逆地理编码的结果列表。
                        public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                            RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();//返回逆地理编码搜索的地理结果
                            //regeocodeAddress.getAois()
                            //返回AOI（面状数据）的数据，如POI名称、区域编码、中心点坐标、POI类型等
                            Log.e("onRegeocodeSearched ",
                                    "逆地理编码建筑名称：" + regeocodeAddress.getBuilding() +
                                            "\n格式化地址：" + regeocodeAddress.getFormatAddress() +
                                            "\n社区名称：" + regeocodeAddress.getNeighborhood() +
                                            "\n乡镇街道编码" + regeocodeAddress.getTowncode() +
                                            "\n乡镇名称" + regeocodeAddress.getTownship()
                            );
                            mLocationLatLng=position;
                            mAddress = regeocodeAddress.getFormatAddress();
                            mTextView_companyName.setText(mAddress);
                        }

                        @Override
                        //根据给定的地理名称和查询城市，返回地理编码的结果列表
                        public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                        }
                    });
                    //latLonPoint参数表示一个Latlng，第二参数表示范围多少米，GeocodeSearch.AMAP表示是国测局坐标系还是GPS原生坐标系
                    LatLonPoint latLonPoint = new LatLonPoint(position.latitude, position.longitude);//LatLonPoint表示一对经、纬度值，以双精度形式存储
                    RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 1000, GeocodeSearch.AMAP);
                    geocodeSearch.getFromLocationAsyn(query);
                }
            }
        });
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_reLocation).setOnClickListener(this);
        findViewById(R.id.imgBack).setOnClickListener(this);
        findViewById(R.id.textView_complete).setOnClickListener(this);
    }

    /**
     * 设置当前位置的Marker点的图标，坐标
     * <p/>
     * //     * @param latLng
     */
    private void moveCenterMarker(LatLng latLng) {
        AMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationClient.stopLocation();//停止定位
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        mLocationClient.onDestroy();//销毁定位客户端。
        //调用销毁功能，在应用的合适生命周期需要销毁附近功能
        NearbySearch.destroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }

    private void setProgressDialog(String text) {
        if (mProgressDialog == null) {
            mProgressDialog = new MyProgressDialog(this, text);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                        mProgressDialog.dismiss();
                        SysApplication.getInstance().exit();
                    }
                    return false;
                }
            });
        } else {

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textView_complete:
                Intent intent = new Intent();
                intent.putExtra("公司地址",mAddress);
                intent.putExtra("公司经度",mLocationLatLng.latitude);
                intent.putExtra("公司纬度",mLocationLatLng.longitude);
                setResult(Constant.RequestAndResultCode.CHOOSE_ADDRESS,intent);
                finishTo();
                break;
            case R.id.imgBack:
                finishTo();
                break;
            case R.id.imageView_reLocation:
                mLocationClient.startLocation();
                break;
        }
    }
}
